package com.leetcode.array.spiralmatrix.demo2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Zan
 * @Create 2024/5/11 15:56
 * @ClassName: Test
 * @Description : https://leetcode.cn/problems/spiral-matrix/description/  螺旋矩阵
 */
public class Test {
    public static void main(String[] args) {

    }
}

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int startX = 0, startY = 0;
        int offset = 1;
        int loop = 1; // 圈数
        int m = matrix.length;
        int n = matrix[0].length;
        int i, j;
        while (loop <= (Math.min(m, n) / 2)) {
            // 跑几圈
            for (j = startY; j < n - offset; j++) {
                // 存入list中
                list.add(matrix[startX][j]);
            }
            for (i = startX; i < m - offset; i++) {
                list.add(matrix[i][j]);
            }
            for (; j > startY; j--) {
                list.add(matrix[i][j]);
            }
            for (; i > startX; i--) {
                list.add(matrix[i][j]);
            }
            startX++;
            startY++;
            offset++;
            loop++;
        }
        if (m == n && (m % 2 == 1)) {
            list.add(matrix[startX][startY]);
        } else if (m != n && (m % 2 == 1 && n % 2 == 0)) {
            for (int z = startY; z < n - offset + 1; z++) {
                list.add(matrix[startX][z]);
            }
        } else if (m != n && (n % 2 == 1 && m % 2 == 0)) {
            for (int z = startX; z < m - offset + 1; z++) {
                list.add(matrix[z][startY]);
            }
        } else if (m != n && (m % 2 == 1 && n % 2 == 1) && m < n) {
            for (int z = startY; z < n - offset + 1; z++) {
                list.add(matrix[startX][z]);
            }
        } else if (m != n && (m % 2 == 1 && n % 2 == 1) && m > n) {
            for (int z = startX; z < m - offset + 1; z++) {
                list.add(matrix[z][startY]);
            }
        }

        return list;
    }
}